package com.ruoyi.form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mongodb.DBRef;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.MongoPage;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.form.base.Def;
import com.ruoyi.form.base.StringUtils;
import com.ruoyi.form.domain.AxModelField;
import com.ruoyi.form.domain.AxField;
import com.ruoyi.form.domain.ResponseResult;
import com.ruoyi.form.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 【表单对应的数据条目】Service业务层处理
 *
 * @author LZF
 * @date 2025-07-18
 */
@Service
public class AxFormDataServiceImpl implements IAxFormDataService {
    @Resource
    IAxModelFieldService axFrontGridService;
    @Resource
    IAxFieldService axFieldService;
    @Resource
    ISysDictDataService sysDictDataService;
    @Resource
    IDataService dataService;
    @Resource
    IMongoService mongoService;
    @Resource
    private MongoTemplate mongoTemplate;
    /**
     * 获取列表配置项
     * @return List
     * @date 2025-06-06
     * @author lzf
     */
    @Override
    public List<AxModelField> queryTableColumnList(String modelId) {
        QueryWrapper<AxModelField> qw = new QueryWrapper<>();
        qw.eq("model_id", modelId);
        qw.eq("show_flag", "0");
        qw.orderByAsc("sort_num");
        // 列显示的引用属性
        List<AxModelField> columnList = axFrontGridService.list(qw);
        if (columnList != null && columnList.size() > 0) {
            for (AxModelField axModelField : columnList) {
                AxField field = axFieldService.selectAxFieldById(axModelField.getFieldId());
                String code = dataService.getPropertyName(field);
                axModelField.setFieldCode(code);
                if (StringUtils.isNotEmpty(field.getFormDictType())) {
                    SysDictData sysDictData = new SysDictData();
                    sysDictData.setDictType(field.getFormDictType());
                    List<SysDictData> sysDictDataList = sysDictDataService.getDictDataList(sysDictData);
                    axModelField.setDictList(sysDictDataList);
                }
            }
        }
        columnList = columnList.stream().sorted((x, y) -> {
            long xSortNum = x.getSortNum();
            long ySortNum = y.getSortNum();
            return (int) (xSortNum - ySortNum);
        }).collect(Collectors.toList());
        return columnList;
    }
    /**
     * 获取筛选项
     * @return List
     * @date 2025-06-06
     * @author lzf
     */
    @Override
    public List<AxModelField>queryFilterColumnList(String modelId) {
        QueryWrapper<AxModelField> qw = new QueryWrapper<>();
        qw.eq("model_id", modelId);
        qw.in("filter_position", Arrays.asList("1", "2", "3"));
        qw.orderByAsc("filter_sort_num");
        List<AxModelField> filterList = axFrontGridService.list(qw);
        if (filterList == null || filterList.size() == 0) {
            return null;
        }
        List<AxModelField> list = new ArrayList<AxModelField>();
        for (AxModelField filter : filterList) {
            AxField field = axFieldService.selectAxFieldById(filter.getFieldId());
            filter.setField(field);
            String code = dataService.getPropertyName(field);
            filter.setFieldCode(code);
            if (StringUtils.isNotEmpty(field.getFormDictType())) {
                SysDictData sysDictData = new SysDictData();
                sysDictData.setDictType(field.getFormDictType());
                List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictData);
                filter.setDictList(sysDictDataList);
                if (field.getFormTypeName().equals("selectztree")) {
                    filter.setDictTree(sysDictDataService.getDictDataTree(sysDictData));
                }
            }
            if ("1".equals(filter.getFilterPosition())) {
                list.add(filter);
            }
        }
        return list;
    }

    /**
     * 根据过滤获取数据列表
     * @return List
     * @date 2025-06-06
     * @author lzf
     */
    @Override
    public TableDataInfo searchDataList(Integer pageNum, Integer pageSize, Map<String, String> map) {
        MongoPage mongoPage = new MongoPage();
        mongoPage.setPageNum(pageNum);
        mongoPage.setPageSize(pageSize);
        List<Bson> bson = new ArrayList<Bson>();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
                    continue;
                }
                if (key.startsWith(Def.PD_)) {
                    String[] dArr = value.split(",");
                    if (dArr.length > 1) {
                        bson.add(Filters.gte(key, dArr[0]));
//                                bson.add(Filters.lte(key, dArr[1]));
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            // 尝试将输入的日期字符串转换为 Date 对象
                            Date endDate = dateFormat.parse(dArr[1]);
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(endDate);
                            calendar.add(Calendar.DATE, 1); // 加一天
                            Date newDate = calendar.getTime();
                            String newDateStr = dateFormat.format(newDate);
                            bson.add(Filters.lte(key, newDateStr));
                        } catch (ParseException e) {
                            System.out.println("输入的字符串不是日期");
                        }
                    }
                } else if (key.startsWith(Def.PC_) && key.contains(Def._D_)) {
                    String[] strArr = value.split(",");
                    if (strArr.length > 0) {
                        bson.add(Filters.in(key, strArr));
                    }
                } else if (key.startsWith(Def.PS_) || key.equals(Def.name)){
                    Pattern pattern = Pattern.compile("^.*" + value + ".*$", Pattern.CASE_INSENSITIVE);
                    bson.add(Filters.regex(key, pattern));
                } else {
                    bson.add(Filters.eq(key, value));
                }
            }
        }
        Bson sort = Sorts.orderBy(Sorts.descending(Def.createTime));
        MongoPage page = mongoService.find(Def.formDataCollection, Filters.and(bson), sort, mongoPage);
        return TableDataInfo.buildMongo(page);
    }
    /**
     * 根据id删除数据
     * @return ResponseResult
     * @date 2025-06-06
     * @author lzf
     */
    @Override
    public ResponseResult deleteKnowLedges(String[] ids) {
        ResponseResult result = new ResponseResult("1", "删除成功");
        for (String id : ids) {
            Query query = new Query(Criteria.where("_id").is(id));
            mongoTemplate.remove(query, Def.formDataCollection);
            DBRef ref = new DBRef(Def.formSubDataCollection, id);
            Bson filter = Filters.and(
                    Filters.eq(Def.parentId, ref)
            );
            mongoService.deleteByFilter(filter, Def.formSubDataCollection);
        }
        return result;
    }
    /**
     * 根据id查询数据详情
     * @return Document
     * @date 2025-06-06
     * @author lzf
     */
    @Override
    public Document getKnowLedgeInfo(String id) {
        return mongoTemplate.findById(id, Document.class, Def.formDataCollection);
    }
    /**
     * 存储前端填报的表单
     * @date 2025-06-06
     * @author lzf
     * @return String id
     */
    @Override
    public String saveKnowLedgeData(Document doc, Boolean apiFlag) {
        boolean isCreateNew = true;
        String _id = doc.getString(Def.id);
        String tplId = doc.getString(Def.TableId);
        Document document;
        if (apiFlag){
            document = dataService.findUseMongoByCode(Def.formDataCollection, doc.getString(Def.code));
        }else {
            document = dataService.findOneUseMongo(doc.getString(Def.id), Def.formDataCollection);
        }
        if (document != null && !document.isEmpty()) {
            isCreateNew = false;
            _id = document.getString(Def.id);
            doc.put(Def.id, _id);
        }
        if (isCreateNew) {//新增
            doc.put(Def.version, doc.containsKey(Def.name)?doc.getInteger(Def.version):1);
        }
        //调用共同处理保存到mongo
        String id = dataService.saveDataUseMongo(tplId, doc.getInteger(Def.version), Def.formDataCollection, doc);
        if (com.ruoyi.common.utils.StringUtils.isBlank(_id)){
            _id = id;
        }
        return _id;
    }

}
